package com.example.shortlink.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.UUID;
import com.alibaba.fastjson2.JSON;
import com.example.shortlink.common.convention.exception.ClientException;
import com.example.shortlink.dao.entity.TUser;
import com.example.shortlink.dao.mapper.TUserMapper;
import com.example.shortlink.dto.req.UserLoginReqDTO;
import com.example.shortlink.dto.req.UserRegisterReqDTO;
import com.example.shortlink.dto.req.UserUpdateReqDTO;
import com.example.shortlink.dto.resp.UserLoginRespDTO;
import com.example.shortlink.dto.resp.UserRespDTO;
import com.example.shortlink.service.GroupService;
import com.example.shortlink.service.UserService;
import com.mybatisflex.core.query.QueryChain;
import com.mybatisflex.core.update.UpdateChain;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.example.shortlink.common.constant.RedisCacheConstant.LOCK_USER_REGISTER_KEY;
import static com.example.shortlink.common.enums.UserErrorCodeEnum.*;
import static com.example.shortlink.dao.entity.table.TUserTableDef.T_USER;

/**
 * @author MSI
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<TUserMapper, TUser> implements UserService {

    private final RedissonClient redissonClient;
    private final StringRedisTemplate stringRedisTemplate;
    private final RBloomFilter<String> userRegisterCachePenetrationBloomFilter;
    private final GroupService groupService;


    /***
     * 根据用户名获取用户信息
     * @param username 用户名
     * @return UserRespDTO 用户信息
     * @throws ClientException 用户不存在
     */
    public UserRespDTO getUserByUsername(String username) {
        log.info("getUserByUsername param username: {}", username);
        return QueryChain.of(mapper)
                .select(T_USER.ID,
                        T_USER.USERNAME,
                        T_USER.REAL_NAME,
                        T_USER.PHONE,
                        T_USER.MAIL)
                .from(T_USER)
                .where(T_USER.USERNAME.eq(username))
                .oneAsOpt(UserRespDTO.class)
                .orElseThrow(() -> new ClientException(USER_NULL));
    }

    /**
     * 查询用户名是否可用
     *
     * @param username 用户名
     * @return 是否可用
     */
    @Override
    public Boolean hasUsername(String username) {
        log.info("hasUsername param username: {}", username);
        // 布隆过滤器查询用户名是否存在
        return !userRegisterCachePenetrationBloomFilter.contains(username);
    }

    /**
     * 注册用户
     *
     * @param requestParam 注册用户请求入参
     */
    @Override
    public void register(UserRegisterReqDTO requestParam) {
        log.info("register param requestParam: {}", requestParam);
        // 校验用户名是否存在
        Boolean hasUsername = this.hasUsername(requestParam.getUsername());
        if (!hasUsername) {
            throw new ClientException(USER_NAME_EXIST);
        }
        // 加锁
        RLock lock = redissonClient.getLock(LOCK_USER_REGISTER_KEY + requestParam.getUsername());
        try {
            if (lock.tryLock()) {
                try {
                    // 保存用户注册信息
                    int inserted = mapper.insert(BeanUtil.toBean(requestParam, TUser.class));
                    // 校验是否保存成功
                    if (inserted < 1) {
                        throw new ClientException(USER_SAVE_ERROR);
                    }
                } catch (DuplicateKeyException ex) {
                    throw new ClientException(USER_EXIST);
                }
                // 缓存用户名
                userRegisterCachePenetrationBloomFilter.add(requestParam.getUsername());
                groupService.saveGroup(requestParam.getUsername(), "默认分组");
                return;
            }
            throw new ClientException(USER_NAME_EXIST);
        } finally {
            // 释放锁
            lock.unlock();
        }
    }

    /**
     * 修改用户
     *
     * @param requestParam 注册用户请求入参
     */
    @Override
    public void modify(UserUpdateReqDTO requestParam) {
        log.info("modify param requestParam:{}", requestParam);
        // TODO 验证当前用户是否为登录用户 - 幂等验证

        // 更新用户信息
        boolean updateFlag = UpdateChain.of(TUser.class)
                .set(T_USER.PASSWORD, requestParam.getPassword())
                .set(T_USER.REAL_NAME, requestParam.getRealName())
                .set(T_USER.PHONE, requestParam.getPhone())
                .set(T_USER.MAIL, requestParam.getMail())
                .where(T_USER.USERNAME.eq(requestParam.getUsername()))
                .update();
        if (!updateFlag) {
            throw new ClientException(USER_UPDATE_ERROR);
        }
    }

    /**
     * 用户登录
     *
     * @param requestParam 用户登录请求入参
     * @return 用户登录信息
     */
    @Override
    public UserLoginRespDTO login(UserLoginReqDTO requestParam) {
        log.info("login param requestParam:{}", requestParam);
        TUser user = QueryChain.of(mapper)
                .select(T_USER.DEFAULT_COLUMNS)
                .where(T_USER.USERNAME.eq(requestParam.getUsername())
                        .and(T_USER.PASSWORD.eq(requestParam.getPassword()))
                        .and(T_USER.DEL_FLAG.eq(Boolean.FALSE)))
                .oneAsOpt(TUser.class)
                .orElseThrow(() -> new ClientException(USER_NULL));
        // 查询 Redis 用户是否是登录状态
        Map<Object, Object> hasLoginMap = stringRedisTemplate.opsForHash().entries("login_" + requestParam.getUsername());
        if (CollUtil.isNotEmpty(hasLoginMap)) {
            String token = hasLoginMap.keySet().stream()
                    .findFirst()
                    .map(Object::toString)
                    .orElseThrow(() -> new ClientException("用户登录错误"));
            return new UserLoginRespDTO(token);
        }
        // Hash Key: login_用户名 Value key: token标识 value: JSON 字符串(用户信息)
        String token = UUID.randomUUID().toString();
        stringRedisTemplate.opsForHash().put("login_" + requestParam.getUsername(), token, JSON.toJSONString(user));
        stringRedisTemplate.expire("login_" + requestParam.getUsername(), 30L, TimeUnit.MINUTES);
        // TODO 返回 jwt 生成的 token
        return new UserLoginRespDTO(token);
    }

    /**
     * 检查用户是否登录
     *
     * @param username 用户名
     * @param token    token
     * @return 是否登录
     */
    @Override
    public Boolean checkLogin(String username, String token) {
        log.info("checkLogin param username: {}, token: {}", username, token);
        return stringRedisTemplate.opsForHash().get("login_" + username, token) != null;
    }

    /**
     * 用户退出登录
     *
     * @param username 用户名
     * @param token    token
     */
    @Override
    public void logout(String username, String token) {
        log.info("logout param username: {}, token: {}", username, token);
        Boolean checkLoginFlag = this.checkLogin(username, token);
        if (checkLoginFlag) {
            stringRedisTemplate.delete("login_" + username);
            return;
        }
        throw new ClientException("用户Token不存在或用户未登录");
    }
}